import os
import ConfigParser

class Configuration:

	def __init__(self,home) :
		self.home = home
		self.gnomeStart = self.home+".config/autostart/gxplanet.desktop"
		self.gxplanetconf = self.home+".gxplanet/"
		self.gxplanetconfF = self.gxplanetconf+"config.cfg"
		if not os.path.isdir(self.gxplanetconf):
			os.system("mkdir "+self.gxplanetconf)

	def startupRemoved(self):
		if os.path.isfile(self.gnomeStart):
			os.system("rm -f "+self.gnomeStart)

	def startupAdded(self):
		if not os.path.isfile(self.gnomeStart):
			file = open(self.gnomeStart,'w')
			file.write("[Desktop Entry]\nName=GxPlanet\nEncoding=UTF-8\nVersion=1.0\nExec=gxplanet\nX-GNOME-Autostart-enabled=true\n")

	def saveConfiguration(self, section, dic):
     		cfg = ConfigParser.RawConfigParser()
		f = file(self.gxplanetconfF,"w")
		cfg.add_section(section)
		keys = dic.keys()
		for key in keys:
     			cfg.set(section,key,dic[key])

     		cfg.write(f)
     		f.close()
     		return True

	def existoldconfig(self):
		return os.path.isfile(self.gxplanetconfF)

	def readconfig(self,section):
		cfg = ConfigParser.ConfigParser()
		try:
			cfg.readfp(file(self.gxplanetconfF))
		except Exception, e:
			print "Error, couldn't read config  ", e
			return
		try:
			if cfg.has_section(section):
				opts = cfg.options(section)
				dic = {}
				for val in opts:
					if cfg.has_option(section,val):
						dic.setdefault(val,cfg.get (section, val.lower()))
				return dic
			return
		except:
			print 'Parameter not Found'
			return 

